﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Ansys.ACT.Interfaces.Analysis;
using Ansys.ACT.Interfaces.Common;
using Ansys.ACT.Interfaces.Mesh;
using Ansys.UI.Toolkit;

namespace AnsysWorkbenchMeshExporter
{
	public class MeshExporter
	{
		public MeshExporter(IAnalysis analysis)
		{
			_analysis = analysis;
		}

		public void DoExport(string filePath)
		{
			var mesh = _analysis.MeshData;
			var components = _analysis.Components;

			//
			var lines = new List<string>();
			lines.Add("* GRIDPOINTS");
			lines.AddRange(mesh.Nodes.Select(node => $"G {node.Id} {node.X:F} {node.Y:F} {node.Z:F}"));

			lines.Add("* ZONES");
			foreach (var elem in mesh.Elements)
			{
				var ids = elem.NodeIds;
				var elemType = elem.Type;
				if (elemType == ElementTypeEnum.kHex8)
				{
					var p1 = ids[0];
					var p2 = ids[1];
					var p3 = ids[2];
					var p4 = ids[3];
					var p5 = ids[4];
					var p6 = ids[5];
					var p7 = ids[6];
					var p8 = ids[7];
					lines.Add($"Z B8 {elem.Id} {p1} {p2} {p4} {p5} {p3} {p8} {p6} {p7}");
				}
				else if (elemType == ElementTypeEnum.kWedge6)
				{
					var p1 = ids[0];
					var p2 = ids[1];
					var p3 = ids[2];
					var p5 = ids[3];
					var p6 = ids[4];
					var p7 = ids[5];
					lines.Add($"Z W6 {elem.Id} {p1} {p3} {p5} {p2} {p7} {p6}");
				}
			}

			lines.Add("* ZGROUPS");
			var comps = components.Where(comp => comp.SelectionType == SelectionTypeEnum.MeshElements && !comp.Name.EndsWith("_"))
				.Select(comp => new {Name = comp.Name, Ids = comp.Ids});
			foreach (var comp in comps)
			{
				lines.Add($"ZGROUP \'{comp.Name}\'");
				var sb = new StringBuilder();
				var idCount = comp.Ids.Count;
				for (int i = 0; i < idCount; i++)
				{
					sb.Append($"{comp.Ids[i]} ");
					const int IdCountEachLine = 15;
					if ((i + 1) % IdCountEachLine == 0)
						sb.AppendLine();
				}
				lines.Add(sb.ToString());

				//MessageBox.Show(comp.Name);
			}

			if (File.Exists(filePath))
				File.Delete(filePath);

			File.WriteAllLines(filePath, lines);
		}

		private IAnalysis _analysis;
	}
}
